
<template>
    <div class="herb-land-overall-comp" ref="herbOverall">
         <TitleBox type=2>
            <template #titlecont>
                <span v-lang="{lang: controlSto.language, lgid: -29}">Overall network</span>
            </template>
        </TitleBox>

         <!-- TODO 就一个1个关系图 -->
        <div class="cont-box">
            <CombinationDiagram
							:dragramTypeList="dragramTypeList"
							@changeTabs="changeTabs"
							:selectTab="selectTab"
							:diagramLenList="dataGraph.diagramLenList"
							@changeShow="changeShow"
							:typeGraph="1"
							:graphRange="graphRange"
							@changeSlider="changeSlider"
							:maxRange="maxRange"
							:dataGraph="dataGraph.data"
							:linksGraph="dataGraph.links"
							:dataTable="dataTable"
							:uiCodeDowm="uiCodeDowm"
							:hotMapX="dataGraph.hotMapX"
							:hotMapY="dataGraph.hotMapY"
							:hotMapData="dataGraph.hotMapData"
							:hotMaxRange="dataGraph.hotMaxRange"
							:templateList="dataTable.templateList"
							@toClkItem="toClkItem"
							:para="dataTable.para"
							:condPage="condPage"
							@chgSize="chgSize"
							@chgCurrnt="chgCurrnt"
							:loading="isLoading"
							:loadingNetWork="dataTable.loadingNetWork"
							:noDataFlag="dataTable.noDataFlag"
            /> 
        </div>
    </div>
</template>

<script setup>
    import { ref, reactive, toRefs, computed, onBeforeMount, watch } from 'vue';
		import { useIntersectionObserver } from '@vueuse/core';
    import TitleBox from '@/components/TitleBox.vue'
    import CombinationDiagram from '@/components/combinationDiagram.vue'
		import { useRouter } from 'vue-router'

    import { langTxt, getFilterThArr, getFilterLangArr } from '@/utils/util'
    import { getHerbnetwork, getTableThList, herbNetworkTable } from '@/service/tcm'
    import { graph, heatmapdata, xLand, yLand, nData } from '@/utils/datagraph.js'

    import { controlStore } from '@/stores/control'
    import { debounce } from 'lodash'
    
    const emitter = defineEmits(['toCalc']);
		const router = useRouter();
    const selectTab = ref(0);
    const graphRange = ref([0, 10])
		const maxRange = ref(10);
		const herbOverall = ref(null);
    let dataGraph = reactive({
			data: [],
			links: [],
			diagramLenList: [],
			hotMapX: [],
			hotMapY: [],
			hotMapData: [],
			hotMaxRange: 2415
		});
    const linksGraph = graph.links;
    const uiCode = ref('overall_network'); //下载表格的code
    const dbData = ref(nData);
    const props = defineProps({
        detailId: {
            type: [Number, String],
            default: ''
        }
    });
    const { detailId } = toRefs(props);
		const uiCodeDowm = ref('herb_network');
    const condPage = reactive({
			pageSize: 10,
			pageNo: 1,
			total: 0
		})
    let searchDebounce = null;

    const controlSto = controlStore();
    const isLoading = ref(true);
    const dragramTypeList = [
		{
			tname: 'Network',
			lgid: '-60',
			code: 'Network'
		}, {
			tname: 'Heatmap',
			lgid: '-61',
			code: 'Heatmap'
		}, {
			tname: 'Table',
			lgid: '-62',
			code: 'Table'
		}
	]
  const changeTabs = (item, index) => {
		selectTab.value = index
		if(index == 0) {
			//关系图
			dataGraph.diagramLenList.forEach(e => {
				e.isShow = true;
			})
		} else if (index == 1) {
			//热力图
		} else if (index == 2) {
			//table
		}
	}
  const changeShow = (item, index, isShow) => {
		// item.isShow = !item.isShow;
		dataGraph.diagramLenList[index].isShow = isShow;
	}
	const changeSlider = (e) => {
		graphRange.value = e;
	}
  const dataTable = reactive({
			filterKey: 'herb_netwrok',
			dTablevt: 1,
			tableConfig: {
				'tooltip-effect': 'dark',
				'highlight-current-row': true,
				stripe: true,
				'header-cell-style': { background: '#BC9F77', color: '#FFF' },
			},
			columnConfig: [],
			dataList: [],
			templateList: [{
					idField: '100716826576557300'
				}, 
				{
					idField: '100716826576557301'
				},
				{
					idField: '100716826576557302'
				},
				{
					idField: '100716826576557303'
				},
			],
			para: {
				langCode:controlSto.language == 1 ? 'ENG': 'CHN',
				herbId: detailId.value,
				uiTypeCode: uiCode.value
			},
			noDataFlag: true,
			loadingNetWork: false
	})
  const condObj = reactive({
    uiCode: 'herb',
	});

  const searchPlace = computed(() => {
		return langTxt(controlSto.language, '-15');
	});

    onBeforeMount(()=> {
			
			const {stop} = useIntersectionObserver(
					herbOverall,
					([{ isIntersecting }], observerElement) => {
							if (isIntersecting) {
									// 停止监听，如果你只想知道一次可视性变化
									toGetTableThList();
									toGetStatistic();
									getTableData();
									//阻止再次请求
									stop()
							}
					},
					{
							threshold: 0, // 当交叉框达到视窗的这部分时触发
					}
			);
    });

    const initDebounce = () => {
        searchDebounce = debounce((e) => {
          //  getDataList();
					toGetStatistic();
					getTableData();
        }, 400);
    };
		const toClkItem = (rowItem, index) => {
			if (!index && index == 1) {
				//herb
				router.push({ name: 'herbdetail', query: {id: rowItem[dataTable.templateList[0].idField]} });
			} else {
				//成分
				router.push({ name: 'ingrdetail', query: {id: rowItem[dataTable.templateList[2].idField]} });
			}
		}

	const toGetTableThList = () => {
		let params = {
            uiCode: uiCode.value,
            langCode: 'ENG,CHN'
        };
		getTableThList(params).then(res => {
			if (res.success) {
						let arr = res.data || [];
						let thArr = getFilterThArr(arr, dataTable.filterKey);
						let langArr = getFilterLangArr(thArr);
						controlSto.setLangList(langArr);
						dataTable.columnConfig = thArr;
				}
		})
	}
    
    const toGetData = () => {
        searchDebounce && searchDebounce();
    };

		const toGetStatistic = () => {
			dataTable.loadingNetWork = true;
			getHerbnetwork({
				langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
				herbId: detailId.value,
				uiTypeCode: uiCode.value
			}).then(res => {
				if (res.success && res.data) {
					dataTable.loadingNetWork = false;
					if (res.data.scatterDiagram) {
						const scatterDiagram = res.data.scatterDiagram;
						if(scatterDiagram.nodeList.length == 0) dataTable.noDataFlag = true;
						else dataTable.noDataFlag = false;

						if (scatterDiagram.links && scatterDiagram.nodeList) {
							let arrXy = [], xyData = [];
							scatterDiagram.links.forEach((e, indx) => {
								if (!indx) {
									maxRange.value = Number(e.distance);
								} else if (maxRange.value < Number(e.distance)) maxRange.value = Number(e.distance);
								graphRange.value = [0, maxRange.value];
								dataGraph.hotMaxRange = maxRange.value;
								// dataGraph.hotMaxRange = 2415;
								scatterDiagram.nodeList.forEach((o, index) => {
									arrXy.push(o.name)
									if (e.source == o.id) e.sourceCategory = o.category;
									if (e.target == o.id) e.targetCategory = o.category;
									o.symbolSize = 10
									// if (o.category == 2) {
									// 		o.symbolSize = 20;
									// 	} else if (o.category == 3) {
									// 		o.symbolSize = 15
									// 	}
									if (!index) {
										o.y = (e.distance * 10) * (Math.floor(Math.random() * (Math.floor(200) + Math.floor(120) + 5)));
										o.x = -(e.distance * 10) * (Math.floor(Math.random() * (Math.floor(200) + Math.floor(120) + 4)));
									}
									if (!o.x) {
										o.y = (e.distance * 10) * (Math.floor(Math.random() * (Math.floor(200) + Math.floor(index) + index)));
										o.x = -(e.distance * 10) * (Math.floor(Math.random() * (Math.floor(200) + Math.floor(index) + index)));
									}
									//线的颜色
									if (e.source ==  o.id && o.category == 2) {
											e.lineStyle = {
												color: '#138848',
												width: 1
											}
									} else if (e.source ==  o.id && o.category == 3) {
										e.lineStyle = {
											color: '#1677FF',
											width: 1
										} 
									} else if (e.source ==  o.id && o.category == 1) {
										e.lineStyle = {
											color: '#BC9F77',
											width: 1
										}
									} else if (e.source ==  o.id && o.category == 4) {
										e.lineStyle = {
											color: '#02BCD5',
											width: 1
										}
									}
									//元素的颜色
									if (o.category == 2) {
											o.itemStyle = {
												color: '#138848'
											}
										} else if(o.category == 3) {
											o.itemStyle = {
												color: '#1677FF'
											}
										} else if(o.category == 1) {
											o.itemStyle = {
												color: '#BC9F77'
											}
										} else if(o.category == 4) {
											o.itemStyle = {
												color: '#02BCD5'
											}
										}
								})
							})
							dataGraph.data = scatterDiagram.nodeList;
							dataGraph.links = scatterDiagram.links;
						
							//处理heatmap数据；
							let _arrXy = new Set(arrXy)
							arrXy = [..._arrXy]
							arrXy.forEach((ex, xind) => {
								arrXy.forEach((ey, yind) => {
									let id1 = '', id2 = '';
									scatterDiagram.nodeList.forEach((enode, nodeind) => {
										if(ex == enode.name) id1 = enode.id;
										if(ey == enode.name) id2 = enode.id;
										
									})
									if (id1 && id2){
										scatterDiagram.links.forEach((elink, linkInd)=> {
											if (id1 == elink.source && elink.target == id2) {
												xyData.push([xind, yind, elink.distance])
												id1 = '';
												id2 = '';
											}
										})
									}
								})
							});
							dataGraph.hotMapData = xyData;
							dataGraph.hotMapX = arrXy.reverse();
							dataGraph.hotMapY = arrXy;
						}
						if(scatterDiagram.contractlist) {
							//diagramLenList
							scatterDiagram.contractlist.forEach((e, index) => {
								e.isShow = true;
								e.id = 'herb_' + index;
								e.source = {
									code: e.sourceCategory,
									name: e.sourceName
								}
								e.target = {
									code: e.targetCategory,
									name: e.targetName
								}
							});
							dataGraph.diagramLenList = scatterDiagram.contractlist
						}
					}
				}
			}).catch((err) => {
				dataTable.noDataFlag = true;
				dataTable.loadingNetWork = false;
			})
		}

	const getTableData = () => {
		isLoading.value = true;
		herbNetworkTable({
			langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
			herbId: detailId.value,
			uiTypeCode: uiCode.value,
			pageSize: condPage.pageSize,
			pageNo: condPage.pageNo
		}).then(res => {
			if (res.success && res.data && res.data.records) {
				isLoading.value = false;
				dataTable.dataList = res.data.records || [];
				condPage.total = res.data.totalCount || 0;
			}
		}).catch(() => {
			isLoading.value = false;
		})
	}
	const chgSize = (e) => {
		condPage.pageSize = e || 10;
    getTableData();
	}
	const chgCurrnt = (e) => {
		condPage.pageNo = e || 1;
    getTableData();
	}
		watch(() => controlSto.language, (n, v) => {
			if (n != v) {
				toGetStatistic();
			}
		})
</script>


<style lang="scss" scoped>
    .herb-land-overall-comp {
        .cont-box {
            padding: 32px 0;
            .plane-box {
                padding-top: 32px;
            }
            .switch-box {
				padding-bottom: 32px;
				text-align: center;
				.switch-wrap {
					display: inline-block;
					border: 1px solid #BC9F77;
					border-radius: 30px;
					font-size: 0;
					color: #967846;
					.switch-item {
						display: inline-block;
						height: 40px;
						width: 200px;
						padding: 0 32px;
						line-height: 40px;
						border-right: 1px solid #BC9F77;
						font-weight: 600;
						font-size: 18px;
						cursor: pointer;
						&:first-child {
							// border-radius: 30px;
							border-top-left-radius: 16px;
							border-bottom-left-radius: 16px;
						}
						&:last-child {
							border-right: none;
							border-top-right-radius: 16px;
							border-bottom-right-radius: 16px;
						}
						&.switch-item-on {
							color: #fff;
							background-color: #BC9F77;
						}
					}
				}

			}
            .switch-cont-box {
                .chart-img {
                    height: 360px;
                    width: 70%;
                    display: flex;
                }
            }
        }
    }
</style>
